package com.vtech.mybatis.baseservice.plugins;

import com.vtech.mybatis.baseservice.util.PluginUtil;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.ArrayList;
import java.util.List;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

/**
 * Service 实现类
 *
 * @author houzhiwei
 * @date 2016 /11/6 22:42.
 */
public class ServiceImplPlugin extends PluginAdapter {
    /**
     * 检测是否有需要的配置参数，没有则不执行插件
     * MapperConfigPlugin
     */
    @Override
    public boolean validate(List<String> warnings) {
        boolean valid = true;

        if (!stringHasValue(properties
                .getProperty("targetProject"))) { //$NON-NLS-1$
            warnings.add(getString("ValidationError.18", //$NON-NLS-1$
                    "MapperConfigPlugin", //$NON-NLS-1$
                    "targetProject")); //$NON-NLS-1$
            valid = false;
        }

        if (!stringHasValue(properties
                .getProperty("targetPackage"))) { //$NON-NLS-1$
            warnings.add(getString("ValidationError.18", //$NON-NLS-1$
                    "MapperConfigPlugin", //$NON-NLS-1$
                    "targetPackage")); //$NON-NLS-1$
            valid = false;
        }

        return valid;
    }

    /**
     * 生成serviceImpl
     */
    @Override
    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(
            IntrospectedTable introspectedTable) {
        // 主键类型
        int keySize = introspectedTable.getPrimaryKeyColumns().size();
        if (keySize > 1) {
            return null;
        }
        // 获取实体类
        FullyQualifiedJavaType entityType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        // 跟接口
        // 参考源码：org.mybatis.generator.codegen.ibatis2.dao.DAOGenerator
        FullyQualifiedJavaType serviceAnnoType = new FullyQualifiedJavaType("org.springframework.stereotype.Service");
        String rootServiceImplClass = properties.getProperty("rootServiceImplClass");
        if (!StringUtility.stringHasValue(rootServiceImplClass)) {
            rootServiceImplClass = "com.vtech.mybatis.baseservice.base.BaseServiceImpl";
        }
        String targetPackage = properties.getProperty("targetPackage");
        String servicePackage = properties.getProperty("servicePackage");
        // 全名

        FullyQualifiedJavaType serviceType = new FullyQualifiedJavaType(targetPackage + "." + entityType.getShortName() + "ServiceImpl");
        TopLevelClass claze = new TopLevelClass(serviceType);
        claze.setVisibility(JavaVisibility.PUBLIC);
        claze.addAnnotation("@Service");

        if (keySize == 0)
            rootServiceImplClass = PluginUtil.insertStr(rootServiceImplClass.lastIndexOf('.') + 1, "NK", rootServiceImplClass);
        FullyQualifiedJavaType rootClassType = new FullyQualifiedJavaType(rootServiceImplClass);
        claze.addImportedType(rootClassType);

        // extends
        StringBuilder superClass = new StringBuilder();
        superClass.append(rootClassType.getShortName());
        superClass.append("<");
        superClass.append(entityType.getShortName());

        if (keySize == 1) {
            FullyQualifiedJavaType primaryKeyType = new FullyQualifiedJavaType(introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().getShortName());
            claze.addImportedType(primaryKeyType);// import 主键类
            superClass.append(",");
            superClass.append(primaryKeyType.getShortName());
        }

        superClass.append(">");
        claze.setSuperClass(new FullyQualifiedJavaType(superClass.toString()));

        claze.addImportedType(serviceAnnoType);

        // import实体类
        claze.addImportedType(entityType);
        // 实现的接口 implements
        FullyQualifiedJavaType superservice = new FullyQualifiedJavaType(servicePackage + "." + entityType.getShortName() + "Service");
        claze.addSuperInterface(superservice);
        claze.addImportedType(superservice);
        GeneratedJavaFile service = new GeneratedJavaFile(claze, properties.getProperty("targetProject"), context.getJavaFormatter());

        List<GeneratedJavaFile> files = new ArrayList<GeneratedJavaFile>(1);

        files.add(service);
        return files;
    }

}
